package com.hue.concurrent.day06;

/**
 * 使用volatile优化两阶段终止模式(优雅的停止一个线程)
 */
public class Demo02 {
    public static void main(String[] args) {
        TwoStop twoStop = new TwoStop();
        twoStop.start();
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        twoStop.stop();
    }

    public static class TwoStop {
        private Thread monitor;
        private boolean flag = true;

        public void start() {
            monitor = new Thread(() -> {
                while (true) {
                    if (Thread.currentThread().isInterrupted() || !flag) {
                        System.out.println("处理后事...");
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                        System.out.println("正常监控...");
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            });
            monitor.start();
        }

        public void stop() {
            flag = false;
            monitor.interrupt();
        }
    }
}
